
'''
#
# 字典的形式实现拆解图片
# PIL可以支持pip install和源码安装 支持python版本>=3.5
'''

from PIL import Image as image

#源图片
old_img ='D:/yu.jpg'
#最终图片 运行后自动生成
new_img ='D:/yu2.jpg'
#目标图片分辨率
newpic_w =800
newpic_h =800
picq =95

def resizeImg(**args):
    #设置基础属性
    args_key ={'old_img':'','new_img':'','newpic_w':'','newpic_h':'','picq':''}
    arg ={}
    for key in args_key:
        if key in args:
            arg[key] =args[key]
            # print("key-------",key)
            # print("args_key------",args_key)
            # print("arg[key]-------",arg[key])
    #读取原来图片分辨率长宽
    im = image.open(arg['old_img'])
    oldpc_w,oldpc_h =im.size
    print("源图片大小",oldpc_w,oldpc_h)

    old_size =float(oldpc_h/oldpc_w)
    print("源图片测量",old_size)
    new_size =float(arg['newpic_h']/arg['newpic_w'])
    print("目标图片测量", new_size)

    # 处理高度
    if old_size >= new_size:
        width =oldpc_w
        height =int(width*new_size)
        x =0
        y=(oldpc_h-height)/3
        print("读这里")

        box = (x, y, width + x, height + y)
        newIm = im.crop(box)
        ratio = float(arg['newpic_w']) / width
        newWidth = int(width * ratio)
        newHeight = int(height * ratio)
        newIm.resize((newWidth, newHeight), image.ANTIALIAS).save(arg['new_img'], quality=arg['picq'])

    #处理宽度
    else:
        height =oldpc_h
        width =int(height*new_size)
        x =(oldpc_w-width)/2
        y=0
        print("读这里")

resizeImg(old_img=old_img,new_img=new_img,newpic_w=newpic_w,newpic_h=newpic_h,picq=picq)